/**
 * Copyright &copy; 2018-2018 <a href="#">聚成科技</a> All rights reserved.
 */
package com.jckj.core.controller;

import com.alibaba.fastjson.JSONObject;
import com.jckj.core.annotation.LogTitle;
import com.jckj.core.exception.DataNotFoundException;
import com.jckj.core.exception.ServiceException;
import com.jckj.core.util.StringUtils;
import com.jckj.core.vos.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *     通用异常处理类
 * </p>
 *
 * @author 刘志远
 * @date 18-1-29
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private final static Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(ServiceException.class)
    public ModelAndView serviceExceptionHanlder(HttpServletRequest request,
                                                  HttpServletResponse response, Object handler, Exception ex){
        LOGGER.error(ex.getMessage(),ex);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("exception", ex.getMessage());
        String header = request.getHeader("X-Requested-With");
        // 处理异步请求
        if (StringUtils.isNotBlank(header) && (header.equals("X-Requested-With") || header.equals("XMLHttpRequest"))) {
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter pw = null;
            try {
                pw = response.getWriter();
                pw.write(JSONObject.toJSONString(Result.error(ex.getMessage())));
                pw.flush();
                pw.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (pw != null) {
                    pw.close();
                }
            }
            return null;
        }
        return new ModelAndView("500", map);
    }

    @ExceptionHandler(DataNotFoundException.class)
    public ModelAndView dataNotFoundptionHanlder(HttpServletRequest request,
                                                HttpServletResponse response, Object handler, Exception ex){
        LOGGER.error(ex.getMessage(),ex);
        Map<String, Object> map = new HashMap<>();
        map.put("exception", ex.getMessage());
        String header = request.getHeader("X-Requested-With");
        // 处理异步请求
        if (StringUtils.isNotBlank(header) && (header.equals("X-Requested-With") || header.equals("XMLHttpRequest"))) {
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter pw = null;
            try {
                pw = response.getWriter();
                pw.write(JSONObject.toJSONString(Result.notFound("未找到要操作的数据")));
                pw.flush();
                pw.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (pw != null) {
                    pw.close();
                }
            }
            return null;
        }
        return new ModelAndView("404", map);
    }

}
